<template>
  <div class="page">
    <a-card class="general-card" title="阈值设置">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <!-- 湿度传感器（%） -->
        <div class="section">
          <div class="section-title">湿度传感器（%）</div>
          <div class="row">
            <el-form-item label="阈值（最大）" prop="humidityMaxThreshold">
              <el-input-number
                v-model="form.humidityMaxThreshold"
                :min="0"
                :controls="false"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="阈值（最小）" prop="humidityMinThreshold">
              <el-input-number
                v-model="form.humidityMinThreshold"
                :min="0"
                :controls="false"
                placeholder="请输入"
              />
            </el-form-item>
          </div>
        </div>

        <!-- 温度传感器（°C） -->
        <div class="section">
          <div class="section-title">温度传感器（°C）</div>
          <div class="row">
            <el-form-item label="阈值（最大）" prop="temperatureMaxThreshold">
              <el-input-number
                v-model="form.temperatureMaxThreshold"
                :min="0"
                :controls="false"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="阈值（最小）" prop="temperatureMinThreshold">
              <el-input-number
                v-model="form.temperatureMinThreshold"
                :min="0"
                :controls="false"
                placeholder="请输入"
              />
            </el-form-item>
          </div>
        </div>

        <div class="footer">
          <el-button type="primary" @click="onSave">保 存</el-button>
          <el-button @click="onReset">重 置</el-button>
        </div>
      </el-form>
    </a-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import type { FormInstance, FormRules } from 'element-plus';
  import { ElMessage } from 'element-plus';

  const formRef = ref<FormInstance>();

  import { thresholdDetailApi, thresholdAddApi } from '@/utils/apiConfig';

  // 默认值与原型一致
  const form = ref({
    humidityMaxThreshold: 60,
    humidityMinThreshold: 0,
    temperatureMaxThreshold: 60,
    temperatureMinThreshold: 0,
  });

  // 基础非负数校验
  const numberNonNegative = (rule: any, value: any, callback: any) => {
    if (value === '' || value === null || value === undefined) {
      return callback(new Error('请输入数值'));
    }
    if (typeof value !== 'number') {
      return callback(new Error('必须为数字'));
    }
    if (value < 0) {
      return callback(new Error('必须为≥0的数字'));
    }
    callback();
  };

  // 交叉校验：最小值不能大于最大值
  const checkRange = (rule: any, value: any, callback: any) => {
    if (
      rule.field === 'humidityMinThreshold' &&
      value > form.value.humidityMaxThreshold
    ) {
      return callback(new Error('最小值不能大于最大值'));
    }
    if (
      rule.field === 'temperatureMinThreshold' &&
      value > form.value.temperatureMaxThreshold
    ) {
      return callback(new Error('最小值不能大于最大值'));
    }
    callback();
  };

  const rules: FormRules = {
    humidityMaxThreshold: [{ validator: numberNonNegative, trigger: 'blur' }],
    humidityMinThreshold: [
      { validator: numberNonNegative, trigger: 'blur' },
      { validator: checkRange, trigger: 'blur' },
    ],
    temperatureMaxThreshold: [
      { validator: numberNonNegative, trigger: 'blur' },
    ],
    temperatureMinThreshold: [
      { validator: numberNonNegative, trigger: 'blur' },
      { validator: checkRange, trigger: 'blur' },
    ],
  };

  const onSave = () => {
    formRef.value?.validate((valid) => {
      if (!valid) return;
      // 通过校验，模拟提交

      const detail = {
        humidityMaxThreshold: form.value.humidityMaxThreshold,
        humidityMinThreshold: form.value.humidityMinThreshold,
        temperatureMaxThreshold: form.value.temperatureMaxThreshold,
        temperatureMinThreshold: form.value.temperatureMinThreshold,
        smokeMaxThreshold: 0,
        smokeMinThreshold: 0,
        offsetXMaxThreshold: 0,
        offsetXMinThreshold: 0,
        offsetYMaxThreshold: 60,
        offsetYMinThreshold: 0,
        offsetZMaxThreshold: 60,
        offsetZMinThreshold: 0,
        slopeMaxThreshold: 60,
        slopeMinThreshold: 0,
      };
      console.log('detail', detail);
      thresholdAddApi(detail).then((res: any) => {
        if (res.code === 200) {
          ElMessage.success('保存成功');
          console.log('提交数据:', form.value);
          // TODO: 在此处调用实际保存接口
        }
      });
    });
  };

  const onReset = () => {
    formRef.value?.resetFields();
  };

  const getInit = async () => {
    const res = await thresholdDetailApi({});
    if (res.code === 200) {
      form.value = res.data;
    }
  };
  onMounted(() => {
    getInit();
  });
</script>

<style lang="less" scoped>
  .page {
    padding: 20px;
  }
  .section {
    margin-bottom: 24px;
  }
  .section-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 16px;
  }
  .row {
    display: flex;
    gap: 40px;
  }
  :deep(.el-input-number) {
    width: 260px;
  }
  .footer {
    margin-top: 16px;
  }
</style>
